<template>
  <view class="page custom-page">
    <custom-head gradient back :title="title">
      <view class="tool" slot="right">
        <!-- <i class="iconfont icon-fenlei fenlei" @click="show = true"></i> -->
        <i :class="{ iconfont: showRight, 'icon-fenlei': showRight, fenlei: showRight }" @click="show = true"></i>
      </view>
    </custom-head>

    <view class="addition">
      <view class="touxiang-box flex col a-center j-c-c">
        <u-upload 
          max-count="1" 
          action="/file/upload"
          :file-list="fileList"
          :form-data="{ type: 'avatar' }"
          :header="{ Authorization: token }"
          :action="BASE_URL + '/file/upload'"
          @on-change="onSuccess"
          @on-remove="omRemove"
        >
          <view class="touxiang" slot="addBtn">
            <image :src="form.avatar" mode="widthFix"></image>
          </view>
        </u-upload>
        <text>学校LOGO</text>
      </view>

      <view class="bottom_content">
        <view class="form">
          <u-form :model="form" ref="uForm" label-width="180">
            <u-form-item label="学校名称" prop="name">
              <u-input v-model="form.name" placeholder="最多16个字符（必填）" />
            </u-form-item>
            <u-form-item label="学校负责人">
              <u-input v-model="form.head" placeholder="请输入学校负责人姓名" />
            </u-form-item>
            <u-form-item label="学校联系电话">
              <u-input v-model="form.phone" placeholder="请输入学校联系电话" />
            </u-form-item>
            <u-form-item label="学校简介">
              <u-input type="textarea" v-model="form.introduction" placeholder="学校简介" />
            </u-form-item>
          </u-form>
        </view>

        <view class="button submit" @click="submit">保存</view>
      </view>

      <u-action-sheet cancelText="取消" :list="list" v-model="show" @click="enterPage"></u-action-sheet>
    </view>
  </view>
</template>
<script>
import { BASE_URL } from '../../api/config'
import { addSchool, getSchoolDetail, updateSchool } from '../../api/modules/school'

export default {
  data() {
    return {
      form: {
        introduction: '',
        name: '',
        head: '',
        phone: '',
        avatar: '../../static/img/avatar.png',
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: ['change', 'blur'],
          }
        ],
      },
      title: '添加学校', // 头部显示学校的名字
      show: false, // 是否批量添加学生信息
      showRight: false,// 是否显示右边按钮
      list: [
        { text: '批量添加学员信息', path: '/pages/student/batchAddition' }
      ],
      static_uri: getApp().globalData.glb_list.config.static_uri, // 获取全局配置文件
      BASE_URL,
      token: uni.getStorageSync('token'),
      fileList: [], // img
    }
  },

  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },

  mounted() {
    if (this.$route?.query?.param && this.$route?.query?.param === '我的学校') {
      this.title = this.$route.query.param
      this.showRight = true // 头部加上后置按钮
    }

    if (this.$route.query.id) {
      // console.log('获取id', this.$route.query.id)
      this._getSchoolDetail(this.$route.query.id)
    }

  },

  methods: {
    omRemove(index) { // 移除照片
			if (index === 0) {
				this.fileList = []
				this.form.avatar = ''
			}
		},
    onSuccess(data) {
      const res = JSON.parse(data.data)
      if (res.code == 201) {
        this.form.avatar = res.data.path
      } else {
        this.$refs.uUpload.clear()
        this.$u.toast('上传失败')
      }
    },
    enterPage(e) { // 是否批量添加学生信息
      let path = this.list[e].path
      // console.log('是否批量添加--', e)
      uni.navigateTo({
        url: path
      })
    },

    submit() {
      this.$refs.uForm.validate(valid => {
        if (valid) {
          
          if (this.$route.query.id) { // 修改
            this._updateSchool(this.$route.query.id, this.form)
          } else {
            this._addschool(this.form)  // 保存页面
          } 
        } else {
          console.log('验证失败');
        }
      });
    },

    _updateSchool(id, data) {
      updateSchool(id, data).then((res) => {
        const { code } = res || {}
        if (code === 201) {
          uni.navigateBack({
              delta: 1
          })
        }
      })
    },

    _addschool(data) {
      addSchool(data).then((res) => {
        if (res.code == 201) {
          this.$u.toast('添加成功')
          this.form = {
            introduction: '',
            name: '',
            head: '',
            phone: ''
          }
          uni.navigateBack({
              delta: 1
          })
        } else {
          this.$u.toast(res.message)
        }
      })
    },

    _getSchoolDetail(id) {  // 获取学校详情
      getSchoolDetail(id).then((res) => {
        const { code, data: { introduction, name, head, phone, avatar } } = res || {};
        if (code === 200) {
          this.form = {
            introduction,
            name,
            head,
            phone,
            avatar: `${this.static_uri}${avatar}`
          };
        }
        console.log('res', res)
      })
    }

  }
}
</script>
<style scoped lang="scss">
.touxiang-box {
  padding: 40rpx 0;
  font-size: 30rpx;
}

.touxiang {
  width: 150rpx !important;
  height: 150rpx !important;
  margin: auto;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: 25rpx;
}

.touxiang image {
  width: 100%;
  height: 100%;
}

.page {
  position: relative;
  height: 100vh;

  .addition {
    height: 100%;
  }
}

.bottom_content {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 0px 45rpx;
  height: calc(100% - 300rpx);
  background-color: #fff;
}

.form {
  background-color: #fff;

  overflow: hidden;
  /* height: 72vh; */

}

.button {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  margin: 80rpx 0 40rpx 0;
  background-color: #2979ff;
  color: #fff;
  font-size: 32rpx;
  text-align: center;
  line-height: 88rpx;
}

/deep/ .u-form-item--left {
  align-items: self-start !important;
}
</style>
